package com.test.utils;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {

    // 解析JSON并获取指定字段的值
    public static String getFieldValue(String jsonString, String fieldName) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            return jsonObject.getJSONObject("data").getString(fieldName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String sendPostRequest(String url, String contentType, String requestBody) {
        try {
            URL connectionUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) connectionUrl.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", contentType);

            // 启用输出流，向服务器发送请求体
            connection.setDoOutput(true);
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(requestBody.getBytes());
            outputStream.flush();
            outputStream.close();

            // 获取响应状态码
            int responseCode = connection.getResponseCode();

            // 从输入流中读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            System.out.println("接口响应信息:"+response);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 返回响应结果
                return response.toString();
            } else {
                // 返回错误信息
                return "Error - Response Code: " + responseCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Exception: " + e.getMessage();
        }
    }

    private static final String applicantPhoneInput = "13488881123";

    public static void main(String[] args) {
        // 构建请求的URL
        String url = "http://m-txc-test.tk.cn/hera_cloud/api/v2/insure/magicCube/wrapper/memberApi/";

        // 设置请求类型
        String contentType = "application/x-www-form-urlencoded";

        // 构建请求体
        String requestBody = "api_s=member.sms&api_m=smscommonsendsms&params={\"mobile\":\"" + applicantPhoneInput + "\",\"type\":\"SMS001\"}";

        // 发送POST请求
        String response = sendPostRequest(url, contentType, requestBody);

        // 输出响应结果
        System.out.println("Response: " + response);

        // 获取"mark"字段的值
        String mark = getFieldValue(response, "mark");

        // 输出"mark"字段的值
        System.out.println("mark: " + mark);

    }

}
